﻿using DoNet.Common.Cache;
using DoNet.Common.Const;
using DoNet.Common.Enums;
using DoNet.Common.Extensions;
using DoNet.Common.Helpers;
using DoNet.Common.Options;
using DoNet.Common.Pages;
using DoNet.Core.DataManager;
using DoNet.Core.Models;
using DoNet.Core.UnitOfWork;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mysqlx.Crud;
using SqlSugar;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DoNet.Core
{
    /// <summary>
    /// 泛型仓储，实现泛型仓储接口
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public class BaseRepository<T> : SimpleClient<T>, IRepository<T> where T : class, new()
    {
        #region 构造函数及基本配置

        /// <summary>
        /// 需要初始化的对象表名
        /// </summary>
        protected string tableName = typeof(T).GetCustomAttribute<SugarTable>()?.TableName ?? string.Empty;

        /// <summary>
        /// 数据库的主键字段名,若主键不是Id请重载BaseRepository设置
        /// </summary>
        protected string primaryKey = "Id";
        /// <summary>
        /// 排序字段
        /// </summary>
        protected string sortField = string.Empty;
        /// <summary>
        /// 是否为降序
        /// </summary>
        protected bool isDescending = true;
        /// <summary>
        /// 选择的字段，默认为所有(*) 
        /// </summary>
        protected string selectedFields = " * ";

        /// <summary>
        /// 数据库配置名称
        /// </summary>
        private static string dbConfigName = "DefaultDb";

        /// <summary>
        /// 
        /// </summary>
        public static bool IsTenant = false;
        /// <summary>
        /// 是否开启多库模式
        /// </summary>
        public static bool MutiDBEnabled = false;

        /// <summary>
        /// 排序字段
        /// </summary>
        public string SortField
        {
            get
            {
                return sortField;
            }
            set
            {
                sortField = value;
            }
        }

        /// <summary>
        /// 数据库访问对象的外键约束
        /// </summary>
        public string PrimaryKey
        {
            get
            {
                return primaryKey;
            }
        }

        public required IConfiguration config;

        public required ILogger logger;
        /// <summary>
        /// 
        /// </summary> 
        public required IUnitOfWork unitOfWork;
        public required IHttpContextAccessor httpContextAccessor;
        /// <summary>
        /// 
        /// </summary>
        public required SqlSugarScope _dbBase;

        /// <summary>
        /// 
        /// </summary>
        public ISqlSugarClient Db
        {
            get { return _dbBase; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        public BaseRepository(IServiceProvider serviceProvider)
        {
            var configService = serviceProvider.GetService<IConfiguration>();
            if (configService != null)
            {
                config = configService;
                IsTenant = config.app("IsTenant").ObjectToBool();
                MutiDBEnabled = config.app("MutiDBEnabled").ObjectToBool();
            }

            var loggerService = serviceProvider.GetService<ILogger>();
            if (loggerService != null)
            {
                logger = loggerService;
            }

            var unitOfWorkService = serviceProvider.GetService<IUnitOfWork>();
            if (unitOfWorkService != null)
            {
                unitOfWork = unitOfWorkService;
                var dbClient = unitOfWork.GetDbClient();
                if (dbClient != null)
                {
                    _dbBase = dbClient;
                }
            }
            var httpContextAccessorService = serviceProvider.GetService<IHttpContextAccessor>();
            if (httpContextAccessorService != null)
            {
                httpContextAccessor = httpContextAccessorService;
            }

            string t = typeof(T).Name;
            var appDbContextAttribute = typeof(T).GetCustomAttribute<AppDbContextAttribute>(false);
            if (appDbContextAttribute != null)
            {
                dbConfigName = appDbContextAttribute.DbConfigName;
            }
            //UserInfo userInfo = GetUserInfo();

            // 获取用户和租户信息
            UserInfo userInfo = null;

            if (IsTenant)
            {
                //CacheHelper cacheHelper = new CacheHelper();

                //ClaimsPrincipal claimsPrincipal = httpContextAccessor.HttpContext?.User;
                //if (claimsPrincipal != null)
                //{
                //    var claims = claimsPrincipal.Claims;
                //    List<Claim> claimList = new List<Claim>();
                //    foreach (var item in claims)
                //    {
                //        claimList.Add(item);
                //    }
                //    if (claimList.Count > 0)
                //    {
                //        userInfo = cacheHelper.Get<UserInfo>(CacheConst.KeyLoginUserInfo + claimList[0].Value);
                //    }
                //    else
                //    {
                //        userInfo = Appsettings.User;
                //    }
                //}
                //if (userInfo != null)
                //{
                //    if (userInfo.TenantName == "default")
                //    {
                //        userInfo = null;
                //    }
                //}
            }


            if (MutiDBEnabled)
            {
                if (userInfo != null)
                {
                    var configId = userInfo.TenantName + "tenant";//租户
                    if (userInfo.TenantSchema == TenantSchemaEnum.AloneDatabase)
                    {
                        #region 独立数据库
                        if (_dbBase != null)
                        {
                            if (!_dbBase.IsAnyConnection(configId))
                            {
                                var listConfig = new List<ConnectionConfig>();
                                List<DbConnections> listdatabase = JsonHelper.DeserializeObject<List<DbConnections>>(userInfo.TenantDataSource) ?? new List<DbConnections>();
                                listdatabase.ForEach(m =>
                                {
                                    ConnectionConfig config = new ConnectionConfig()
                                    {
                                        ConfigId = m.ConnId,
                                        ConnectionString = m.MasterDB.ConnectionString,
                                        DbType = (DbType)m.MasterDB.DatabaseType,
                                        IsAutoCloseConnection = true
                                    };
                                    if (m.ReadDB != null)
                                    {
                                        List<SlaveConnectionConfig> slaveConnectionConfigs = new List<SlaveConnectionConfig>();
                                        m.ReadDB.ForEach(r =>
                                        {
                                            if (r.Enabled)
                                            {
                                                slaveConnectionConfigs.Add(new SlaveConnectionConfig()
                                                {
                                                    HitRate = r.HitRate,
                                                    ConnectionString = r.ConnectionString
                                                });
                                            }
                                        });
                                        config.SlaveConnectionConfigs = slaveConnectionConfigs;
                                    }
                                    _dbBase.AddConnection(config);
                                });
                                _dbBase.ChangeDatabase(configId);
                            }
                            else
                            {
                                _dbBase.ChangeDatabase(configId);
                            }
                        }
                        #endregion
                    }
                    else if (userInfo.TenantSchema == TenantSchemaEnum.ShareSchema)
                    {

                    }
                }
                else
                {
                    if (_dbBase != null)
                    {
                        _dbBase.ChangeDatabase(dbConfigName.ToLower());
                    }
                }
            }
        }
        #endregion

        #region SqlSugar 操作

        #region 同步方法
        #region 同步新增
        /// <summary>
        /// 同步新增实体。
        /// </summary>
        /// <param name="entitie">实体</param>
        /// <returns></returns>
        public virtual new int Insert(T entitie)
        {
            return Db.Insertable(entitie).UseParameter().ExecuteCommand();
        }
        /// <summary>
        /// 同步批量新增实体。
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns></returns>
        public virtual int Insert(IEnumerable<T> entities)
        {
            var list = entities.ToList();
            if (list.Count <= 500)
            {
                return Db.Insertable(entities.ToList()).UseParameter().ExecuteCommand();
            }
            else
            {
                return Db.Fastest<T>().BulkCopy(entities.ToList());
            }
        }
        /// <summary>
        /// 同步新增或更新
        /// </summary>
        /// <param name="entities"></param>
        /// <returns>(返回新增数量, 返回更新数量)</returns>
        public virtual Tuple<int, int> InsertOrUpdate(IEnumerable<T> entities)
        {
            int insertNum = 0; int updateNum = 0;
            try
            {
                var storage = Db.Storageable(entities.ToList()).ToStorage(); //将数据进行分组 
                insertNum = storage.AsInsertable.ExecuteCommand(); //执行插入 （可以换成雪花ID和自增）
                updateNum = storage.AsUpdateable.ExecuteCommand(); //执行更新　
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }
            return new Tuple<int, int>(insertNum, updateNum);
        }
        #endregion 同步新增

        #region 同步修改
        /// <summary>
        /// 同步按条件更新
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool Update(T entity, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable<T>(entity);
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            return update.ExecuteCommandHasChange();
        }
        /// <summary>
        /// 同步按条件更新指定字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="listColumns">需要更新的字段</param>
        /// <param name="listIgnoreColumns">不用更新的字段</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool Update(T entity, IEnumerable<string> listColumns, IEnumerable<string> listIgnoreColumns)
        {
            var update = Db.Updateable(entity);
            if (listColumns != null)
            {
                string[] arrayColumns = listColumns.ToArray();
                if (arrayColumns.Length > 0)
                {
                    update = update.UpdateColumns(arrayColumns);
                }
            }
            if (listIgnoreColumns != null)
            {
                string[] arrayIgnoreColumns = listIgnoreColumns.ToArray();
                if (arrayIgnoreColumns.Length > 0)
                {
                    update = update.IgnoreColumns(arrayIgnoreColumns);
                }
            }
            return update.ExecuteCommandHasChange();
        }
        /// <summary>
        /// 同步按条件更新指定字段
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="listColumns">需要更新的字段</param>
        /// <param name="listIgnoreColumns">不用更新的字段</param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool Update(IEnumerable<T> entitys, IEnumerable<string> listColumns, IEnumerable<string> listIgnoreColumns, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable(entitys.ToList());
            if (listColumns != null)
            {
                string[] arrayColumns = listColumns.ToArray();
                if (arrayColumns.Length > 0)
                {
                    update = update.UpdateColumns(arrayColumns);
                }
            }
            if (listIgnoreColumns != null)
            {
                string[] arrayIgnoreColumns = listIgnoreColumns.ToArray();
                if (arrayIgnoreColumns.Length > 0)
                {
                    update = update.IgnoreColumns(arrayIgnoreColumns);
                }
            }
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            try
            {
                return update.ExecuteCommandHasChange();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return false;
        }
        /// <summary>
        /// 异步根据id更新
        /// </summary>
        /// <param name="columns">更新的列及值</param>
        /// <param name="id"></param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool Update(Expression<Func<T, T>> columns, long id)
        {
            return Update(columns, "Id=@PrimaryKey", new { PrimaryKey = id });
        }
        /// <summary>
        /// 同步按条件更新（条件语句为空或者条件参数为null时，就代表没有条件，因此使用此方法需谨慎）
        /// </summary>
        /// <param name="columns">更新的列及值</param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool Update(Expression<Func<T, T>> columns, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable<T>().SetColumns(columns);
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            try
            {
                return update.ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return false;
        }
        #endregion  同步修改

        #region 同步查询
        #region 单个实体
        /// <summary>
        /// 同步根据主键查询单个实体。
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public virtual T GetById(long id)
        {
            return Db.Queryable<T>().InSingle(id);
        }
        /// <summary>
        /// 同步根据条件获取一个对象
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual T? GetByWhere(string whereSql = "", object? parameters = null)
        {
            return GetListByWhere(whereSql, parameters)?.First();
        }
        /// <summary>
        /// 同步根据条件获取一个对象
        /// 用于返回查询结果的第一条记录，但如果查询结果为空，它将返回 default(T) 值（通常是 null 对于引用类型）
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual T GetFirstByWhere(Expression<Func<T, bool>> whereExpression)
        {
            return GetFirst(whereExpression);
        }
        /// <summary>
        /// 同步根据条件获取一个对象
        /// 用于返回一个单一的结果，如果查询结果有多于一个结果，它会抛出一个异常（通常是 InvalidOperationException)
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual T GetSingleByWhere(Expression<Func<T, bool>> whereExpression)
        {
            return GetSingle(whereExpression);
        }
        #endregion 单个实体

        #region 实体列表
        /// <summary>
        /// 同步获取所有数据，谨慎使用
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<T> GetAll()
        {
            return GetList();
        }
        /// <summary>
        /// 同步根据查询条件获取数据集合
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual IEnumerable<T>? GetListByWhere(string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if(!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            try
            {
                return query.ToList();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return default;
        }
        /// <summary>
        /// 同步根据查询条件获取数据集合
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual IEnumerable<T> GetListByWhere(Expression<Func<T, bool>> whereExpression)
        {
            return Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).ToList();
        }
        /// <summary>
        /// 同步根据查询条件查询前多少条数据
        /// SQL语句，仅支持SqlServer和Mysql
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual IEnumerable<T> GetListTopWhere(int top, Expression<Func<T, bool>> whereExpression)
        {
            return Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).Take(top).ToList();
        }
        /// <summary>
        /// 同步根据查询条件查询前多少条数据
        /// SQL语句，仅支持SqlServer和Mysql
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual IEnumerable<T>? GetListTopWhere(int top, string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            try
            {
                return query.Take(top).ToList();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return default;
        }
        /// <summary>
        /// 同步查询对应有效状态的数据
        /// </summary>
        /// <param name="enabledMark">有效状态</param>
        /// <returns></returns>
        public virtual IEnumerable<T>? GetAllByEnabledMark(bool enabledMark)
        {
            return GetListByWhere("EnabledMark=@EnabledMark", new { EnabledMark = enabledMark });
        }
        /// <summary>
        /// 同步查询软删除状态的数据
        /// </summary>
        /// <param name="deleteMark">软删除状态</param>
        /// <returns></returns>
        public virtual IEnumerable<T>? GetAllByDeleteMark(bool deleteMark)
        {
            return GetListByWhere("DeleteMark=@DeleteMark", new { DeleteMark = deleteMark });
        }
        /// <summary>
        /// 同步查询未软删除且有效的数据，如果查询条件为空，即查询所有数据
        /// </summary>
        /// <param name="deleteMark">软删除状态</param>
        /// <param name="enabledMark">有效状态</param>
        /// <returns></returns>
        public virtual IEnumerable<T>? GetAllByDeleteMarkAndEnabledMark(bool deleteMark, bool enabledMark)
        {
            return GetListByWhere("DeleteMark=@DeleteMark and EnabledMark=@EnabledMark", new { DeleteMark = deleteMark, EnabledMark = enabledMark });
        }
        #endregion 实体列表

        #region 分页实体列表
        /// <summary>
        /// 同步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <returns>指定对象的集合</returns>
        public virtual List<T> FindWithPager(string condition, PagerInfo info)
        {
            return FindWithPager(condition, info, this.SortField, this.isDescending);
        }
        /// <summary>
        /// 同步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <returns>指定对象的集合</returns>
        public virtual List<T> FindWithPager(string condition, PagerInfo info, string fieldToSort)
        {
            return FindWithPager(condition, info, fieldToSort, this.isDescending);
        }
        /// <summary>
        /// 同步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段，如name asc,age desc</param>
        /// <param name="desc">排序方式 true为desc，false为asc</param>
        /// <returns>指定对象的集合</returns>
        public virtual List<T> FindWithPager(string condition, PagerInfo info, string fieldToSort, bool desc)
        {
            List<T> list = new List<T>();

            if (HasInjectionData(condition))
            {
                logger.LogError(string.Format("检测出SQL注入的恶意数据, {0}", condition));
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(condition))
            {
                condition = "1=1";
            }
            if (desc)
            {
                fieldToSort += " desc";
            }

            int totalCount = 0;
            list = Db.Queryable<T>().OrderByIF(!string.IsNullOrEmpty(fieldToSort), fieldToSort).WhereIF(!string.IsNullOrEmpty(condition), condition).ToPageList(info.CurrenetPageIndex, info.PageSize, ref totalCount);
            info.RecordCount = totalCount;
            return list;
        }
        /// <summary>
        /// 同步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="whereExpression">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns>指定对象的集合</returns>
        public virtual List<T> FindWithPager(Expression<Func<T, bool>> whereExpression, PagerInfo info, string fieldToSort, bool desc)
        {
            List<T> list = new List<T>();
            if (desc)
            {
                fieldToSort += " desc";
            }
            int totalCount = 0;
            list = Db.Queryable<T>().OrderByIF(!string.IsNullOrEmpty(fieldToSort), fieldToSort).WhereIF(whereExpression != null, whereExpression).ToPageList(info.CurrenetPageIndex, info.PageSize, ref totalCount);
            info.RecordCount = totalCount;
            return list;
        }
        #endregion 分页实体列表

        #region Count、Max、Min、Sum
        /// <summary>
        /// 同步根据条件统计数据（sql语句方法）
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual int GetCountByWhere(string whereSql = "", object? parameters = null)
        {
            try
            {
                var query = Db.Queryable<T>();
                if (!string.IsNullOrEmpty(whereSql) && parameters != null)
                {
                    query = query.Where(whereSql, parameters);
                }
                return query.Count();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return 0;
        }
        /// <summary>
        /// 同步根据条件统计数据（表达式方法）
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual int GetCountByWhere(Expression<Func<T, bool>> whereExpression)
        {
            return Count(whereExpression);
        }
        /// <summary>
        /// 同步根据条件查询获取某个字段的最大值（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">最大值的数据类型</typeparam>
        /// <param name="maxField">最大值的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns>返回字段的最小值</returns>
        public virtual TResult? GetMaxValueByField<TResult>(string maxField, string whereSql = "", object? parameters = null)
        {
            try
            {
                var query = Db.Queryable<T>();
                if (!string.IsNullOrEmpty(whereSql) && parameters != null)
                {
                    query = query.Where(whereSql, parameters);
                }
                return query.Max<TResult>(maxField);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return default;
        }
        /// <summary>
        /// 同步根据条件查询获取某个字段的最大值（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">最大值的数据类型</typeparam>
        /// <param name="maxFieldExpression">最大值字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns>返回字段的最小值</returns>
        public virtual TResult GetMaxValueByField<TResult>(Expression<Func<T, TResult>> maxFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).Max<TResult>(maxFieldExpression);
        }
        /// <summary>
        /// 同步根据条件查询获取某个字段的最小值（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">最小值的数据类型</typeparam>
        /// <param name="minField">最小值的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns>返回字段的最小值</returns>
        public virtual TResult? GetMinValueByField<TResult>(string minField, string whereSql = "", object? parameters = null)
        {
            try
            {
                var query = Db.Queryable<T>();
                if (!string.IsNullOrEmpty(whereSql) && parameters != null)
                {
                    query = query.Where(whereSql, parameters);
                }
                return query.Min<TResult>(minField);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return default;
        }
        /// <summary>
        /// 同步根据条件查询获取某个字段的最小值（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">最小值的数据类型</typeparam>
        /// <param name="minFieldExpression">最小值字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns>返回字段的最小值</returns>
        public virtual TResult GetMinValueByField<TResult>(Expression<Func<T, TResult>> minFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).Min<TResult>(minFieldExpression);
        }
        /// <summary>
        /// 同步根据条件统计某个字段之和,sum(字段)（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">求和后的数据类型</typeparam>
        /// <param name="sumField">求和的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual TResult GetSumValueByField<TResult>(string sumField, string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            return query .Sum<TResult>(sumField);
        }
        /// <summary>
        /// 同步根据条件统计某个字段之和,sum(字段)（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">求和后的数据类型</typeparam>
        /// <param name="sumFieldExpression">求和字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual TResult GetSumValueByField<TResult>(Expression<Func<T, TResult>> sumFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).Sum<TResult>(sumFieldExpression);
        }
        #endregion Count、Max、Min、Sum
        #endregion 同步查询

        #region 同步删除
        /// <summary>
        /// 同步按主键批量删除
        /// </summary>
        /// <param name="ids">主键Id List集合</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool DeleteById(long id)
        {
            return DeleteByWhere("Id=@PrimaryKey", new { PrimaryKey = id });
        }
        /// <summary>
        /// 同步按主键批量删除
        /// </summary>
        /// <param name="ids">主键Id List集合</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual bool DeleteByIds(IEnumerable<long> ids)
        {
            return DeleteByIds(ids.Select(x => (dynamic)x).ToArray());
        }
        /// <summary>
        /// 异步按条件删除
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数及值 如：new { Age = 30 }</param>
        /// <returns></returns>
        public virtual bool DeleteByWhere(string whereSql = "", object? parameters = null)
        {
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                try
                {
                    return Db.Deleteable<T>().Where(whereSql, parameters).ExecuteCommand() > 0;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
                }
            }
            return false;
        }
        #endregion 同步删除

        #region 事务
        /// <summary>
        /// 同步多表多数据操作批量插入、更新、删除--事务
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="commandTimeout">超时</param>
        /// <returns></returns>
        public Tuple<bool, string> ExecuteTransaction(List<Tuple<string, object?>> trans, int? commandTimeout = null)
        {
            if (trans.Count == 0) return new Tuple<bool, string>(false, "执行事务SQL语句不能为空！");
            unitOfWork.BeginTran();
            try
            {
                foreach (var tran in trans)
                {
                    Db.Ado.ExecuteCommand(tran.Item1, tran.Item2);
                }
                //提交事务
                unitOfWork.CommitTran();
                return new Tuple<bool, string>(true, string.Empty);
            }
            catch (Exception ex)
            {
                //回滚事务
                logger.LogError(ex.ToString());
                unitOfWork.RollbackTran();
                return new Tuple<bool, string>(false, ex.ToString());
            }
        }
        /// <summary>
        /// 同步使用事务
        /// </summary>
        /// <param name="action">事务执行的方法</param>
        /// <returns></returns>
        public DbResult<bool> TransactionExecute(Action action)
        {
            return Db.Ado.UseTran(() => action());
        }
        #endregion 事务
        #endregion 同步方法

        #region 异步方法
        #region 异步新增
        /// <summary>
        /// 异步新增实体。
        /// </summary>
        /// <param name="entitie">实体</param>
        /// <returns></returns>
        public virtual new async Task<int> InsertAsync(T entitie)
        {
            return await Db.Insertable(entitie).UseParameter().ExecuteCommandAsync();
        }
        /// <summary>
        /// 异步批量新增实体。
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns></returns>
        public virtual async Task<int> InsertAsync(IEnumerable<T> entities)
        {
            var list = entities.ToList();
            if (list.Count <= 500)
            {
                return await Db.Insertable(list).UseParameter().ExecuteCommandAsync();
            }
            else
            {
                return await Db.Fastest<T>().BulkCopyAsync(list);
            }
        }
        /// <summary>
        /// 异步新增或更新
        /// </summary>
        /// <param name="entities">数据集合</param>
        /// <returns>(返回新增数量, 返回更新数量)</returns>
        public virtual async Task<Tuple<int, int>> InsertOrUpdateAsync(IEnumerable<T> entities)
        {
            int insertNum = 0; int updateNum = 0;
            try
            {
                var storage = await Db.Storageable(entities.ToList()).ToStorageAsync(); //将数据进行分组 
                insertNum = await storage.AsInsertable.ExecuteCommandAsync(); //执行插入 （可以换成雪花ID和自增）
                updateNum = await storage.AsUpdateable.ExecuteCommandAsync(); //执行更新　
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }
            return new Tuple<int, int>(insertNum, updateNum);
        }
        #endregion 异步新增

        #region 异步修改
        /// <summary>
        /// 异步按条件更新
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> UpdateAsync(T entity, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable<T>(entity);
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            return await update.ExecuteCommandHasChangeAsync();
        }
        /// <summary>
        /// 异步按条件更新指定字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="listColumns">需要更新的字段</param>
        /// <param name="listIgnoreColumns">不用更新的字段</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> UpdateAsync(T entity, IEnumerable<string> listColumns, IEnumerable<string> listIgnoreColumns)
        {
            var update = Db.Updateable(entity);
            if (listColumns != null)
            {
                string[] arrayColumns = listColumns.ToArray();
                if (arrayColumns.Length > 0)
                {
                    update = update.UpdateColumns(arrayColumns);
                }
            }
            if (listIgnoreColumns != null)
            {
                string[] arrayIgnoreColumns = listIgnoreColumns.ToArray();
                if (arrayIgnoreColumns.Length > 0)
                {
                    update = update.IgnoreColumns(arrayIgnoreColumns);
                }
            }
            return await update.ExecuteCommandHasChangeAsync();
        }
        /// <summary>
        /// 异步按条件更新指定字段
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="listColumns">需要更新的字段</param>
        /// <param name="listIgnoreColumns">不用更新的字段</param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> UpdateAsync(IEnumerable<T> entitys, IEnumerable<string> listColumns, IEnumerable<string> listIgnoreColumns, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable(entitys.ToList());
            if (listColumns != null)
            {
                string[] arrayColumns = listColumns.ToArray();
                if (arrayColumns.Length > 0)
                {
                    update = update.UpdateColumns(arrayColumns);
                }
            }
            if (listIgnoreColumns != null)
            {
                string[] arrayIgnoreColumns = listIgnoreColumns.ToArray();
                if (arrayIgnoreColumns.Length > 0)
                {
                    update = update.IgnoreColumns(arrayIgnoreColumns);
                }
            }
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            try
            {
                return await update.ExecuteCommandHasChangeAsync();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return false;
        }
        /// <summary>
        /// 异步根据id更新
        /// </summary>
        /// <param name="columns">更新的列及值</param>
        /// <param name="id"></param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> UpdateAsync(Expression<Func<T, T>> columns, long id)
        {
            return await UpdateAsync(columns, "Id=@PrimaryKey", new { PrimaryKey = id });
        }
        /// <summary>
        /// 异步按条件更新（条件语句为空或者条件参数为null时，就代表没有条件，因此使用此方法需谨慎）
        /// </summary>
        /// <param name="columns">更新的列及值</param>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数 如：new { Age = 30 }</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> UpdateAsync(Expression<Func<T, T>> columns, string whereSql = "", object? parameters = null)
        {
            var update = Db.Updateable<T>().SetColumns(columns);
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                update = update.Where(whereSql, parameters);
            }
            try
            {
                return await update.ExecuteCommandAsync() > 0;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
            }
            return false;
        }
        #endregion  异步修改

        #region 异步查询
        #region 单个实体
        /// <summary>
        /// 异步根据主键查询单个实体。
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public virtual async Task<T> GetByIdAsync(long id)
        {
            return await Db.Queryable<T>().InSingleAsync(id);
        }
        /// <summary>
        /// 异步根据条件获取一个对象
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual async Task<T> GetByWhereAsync(string whereSql, object parameters)
        {
            return (await GetListByWhereAsync(whereSql, parameters)).First();
        }
        /// <summary>
        /// 异步根据条件获取一个对象
        /// 用于返回查询结果的第一条记录，但如果查询结果为空，它将返回 default(T) 值（通常是 null 对于引用类型）
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<T> GetFirstByWhereAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await GetFirstAsync(whereExpression);
        }
        /// <summary>
        /// 异步根据条件获取一个对象
        /// 用于返回一个单一的结果，如果查询结果有多于一个结果，它会抛出一个异常（通常是 InvalidOperationException)
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual async Task<T> GetSingleByWhereAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await GetSingleAsync(whereExpression);
        }
        #endregion 单个实体

        #region 实体列表
        /// <summary>
        /// 异步获取所有数据，谨慎使用
        /// </summary>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetAllAsync()
        {
            return await GetListAsync();
        }
        /// <summary>
        /// 异步根据查询条件获取数据集合
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetListByWhereAsync(string whereSql, object parameters)
        {
            return await Db.Queryable<T>().Where(whereSql, parameters).ToListAsync();
        }
        /// <summary>
        /// 异步根据查询条件获取数据集合
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetListByWhereAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }
        /// <summary>
        /// 异步根据查询条件查询前多少条数据
        /// SQL语句，仅支持SqlServer和Mysql
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetListTopWhereAsync(int top, Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Queryable<T>().Take(top).WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }
        /// <summary>
        /// 异步根据查询条件查询前多少条数据
        /// SQL语句，仅支持SqlServer和Mysql
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetListTopWhereAsync(int top, string whereSql, object parameters)
        {
            return await Db.Queryable<T>().Take(top).Where(whereSql, parameters).ToListAsync();
        }
        /// <summary>
        /// 异步查询对应有效状态的数据
        /// </summary>
        /// <param name="enabledMark">有效状态</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetAllByEnabledMarkAsync(bool enabledMark)
        {
            return await GetListByWhereAsync("EnabledMark=@EnabledMark", new { EnabledMark = enabledMark });
        }
        /// <summary>
        /// 异步查询软删除状态的数据
        /// </summary>
        /// <param name="deleteMark">软删除状态</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetAllByDeleteMarkAsync(bool deleteMark)
        {
            return await GetListByWhereAsync("DeleteMark=@DeleteMark", new { DeleteMark = deleteMark });
        }
        /// <summary>
        /// 异步查询未软删除且有效的数据，如果查询条件为空，即查询所有数据
        /// </summary>
        /// <param name="deleteMark">软删除状态</param>
        /// <param name="enabledMark">有效状态</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetAllByDeleteMarkAndEnabledMarkAsync(bool deleteMark, bool enabledMark)
        {
            return await GetListByWhereAsync("DeleteMark=@DeleteMark and EnabledMark=@EnabledMark", new { DeleteMark = deleteMark, EnabledMark = enabledMark });
        }
        #endregion 实体列表

        #region 分页实体列表
        /// <summary>
        /// 异步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <returns>指定对象的集合</returns>
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info)
        {
            return await FindWithPagerAsync(condition, info, this.SortField);
        }
        /// <summary>
        /// 异步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <returns>指定对象的集合</returns>
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort)
        {
            return await FindWithPagerAsync(condition, info, fieldToSort, this.isDescending);
        }
        /// <summary>
        /// 异步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">排序方式 true为desc，false为asc</param>
        /// <returns>指定对象的集合</returns>
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort, bool desc)
        {
            List<T> list = new List<T>();
            if (HasInjectionData(condition))
            {
                logger.LogError(string.Format("检测出SQL注入的恶意数据, {0}", condition));
                throw new Exception("检测出SQL注入的恶意数据");
            }
            //if (string.IsNullOrEmpty(condition))
            //{
            condition = "1=1 " + condition;
            //}
            if (desc)
            {
                fieldToSort += " desc";
            }
            RefAsync<int> totalCount = 0;
            list = await Db.Queryable<T>().OrderByIF(!string.IsNullOrEmpty(fieldToSort), fieldToSort).WhereIF(!string.IsNullOrEmpty(condition), condition).ToPageListAsync(info.CurrenetPageIndex, info.PageSize, totalCount);
            info.RecordCount = totalCount;
            return list;
        }
        /// <summary>
        /// 异步根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="whereExpression">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns>指定对象的集合</returns>
        public virtual async Task<List<T>> FindWithPagerAsync(Expression<Func<T, bool>> whereExpression, PagerInfo info, string fieldToSort, bool desc)
        {
            List<T> list = new List<T>();
            if (desc)
            {
                fieldToSort += " desc";
            }
            RefAsync<int> totalCount = 0;
            list = await Db.Queryable<T>().OrderByIF(!string.IsNullOrEmpty(fieldToSort), fieldToSort).WhereIF(whereExpression != null, whereExpression).ToPageListAsync(info.CurrenetPageIndex, info.PageSize, totalCount);
            info.RecordCount = totalCount;
            return list;
        }
        #endregion 分页实体列表

        #region Count、Max、Min、Sum
        /// <summary>
        /// 异步根据条件统计数据（sql语句方法）
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual async Task<int> GetCountByWhereAsync(string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            return await query.CountAsync();
        }
        /// <summary>
        /// 异步根据条件统计数据（表达式方法）
        /// </summary>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual async Task<int> GetCountByWhereAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await CountAsync(whereExpression);
        }
        /// <summary>
        /// 异步根据条件查询获取某个字段的最大值（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">最大值的数据类型</typeparam>
        /// <param name="maxField">最大值的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns>返回字段的最小值</returns>
        public virtual async Task<TResult> GetMaxValueByFieldAsync<TResult>(string maxField, string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            return await query.MaxAsync<TResult>(maxField);
        }
        /// <summary>
        /// 异步根据条件查询获取某个字段的最大值（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">最大值的数据类型</typeparam>
        /// <param name="maxFieldExpression">最大值字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns>返回字段的最小值</returns>
        public virtual async Task<TResult> GetMaxValueByFieldAsync<TResult>(Expression<Func<T, TResult>> maxFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).MaxAsync<TResult>(maxFieldExpression);
        }
        /// <summary>
        /// 异步根据条件查询获取某个字段的最小值（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">最小值的数据类型</typeparam>
        /// <param name="minField">最小值的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns>返回字段的最小值</returns>
        public virtual async Task<TResult> GetMinValueByFieldAsync<TResult>(string minField, string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            return await query.MinAsync<TResult>(minField);
        }
        /// <summary>
        /// 异步根据条件查询获取某个字段的最小值（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">最小值的数据类型</typeparam>
        /// <param name="minFieldExpression">最小值字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns>返回字段的最小值</returns>
        public virtual async Task<TResult> GetMinValueByFieldAsync<TResult>(Expression<Func<T, TResult>> minFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).MinAsync<TResult>(minFieldExpression);
        }
        /// <summary>
        /// 异步根据条件统计某个字段之和,sum(字段)（sql语句方法）
        /// </summary>
        /// <typeparam name="TResult">求和后的数据类型</typeparam>
        /// <param name="sumField">求和的字段名称</param>
        /// <param name="whereSql">条件语句 如："Age=@Age"</param>
        /// <param name="parameters">条件参数 如：new { Age=30 }</param>
        /// <returns></returns>
        public virtual async Task<TResult> GetSumValueByFieldAsync<TResult>(string sumField, string whereSql = "", object? parameters = null)
        {
            var query = Db.Queryable<T>();
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                query = query.Where(whereSql, parameters);
            }
            return await query.SumAsync<TResult>(sumField);
        }
        /// <summary>
        /// 异步根据条件统计某个字段之和,sum(字段)（表达式方法）
        /// </summary>
        /// <typeparam name="TResult">求和后的数据类型</typeparam>
        /// <param name="sumFieldExpression">求和字段表达式</param>
        /// <param name="whereExpression">查询条件表达式</param>
        /// <returns></returns>
        public virtual async Task<TResult> GetSumValueByFieldAsync<TResult>(Expression<Func<T, TResult>> sumFieldExpression, Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Queryable<T>().WhereIF(whereExpression != null, whereExpression).SumAsync<TResult>(sumFieldExpression);
        }
        #endregion Count、Max、Min、Sum
        #endregion 异步查询

        #region 异步删除
        /// <summary>
        /// 异步按主键删除
        /// </summary>
        /// <param name="id">主键Id List集合</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> DeleteByIdAsync(long id)
        {
            return await DeleteByWhereAsync("Id=@PrimaryKey", new { PrimaryKey = id });
        }
        /// <summary>
        /// 异步按主键批量删除
        /// </summary>
        /// <param name="ids">主键Id List集合</param>
        /// <returns>执行成功返回true，否则为false。</returns>
        public virtual async Task<bool> DeleteByIdsAsync(IEnumerable<long> ids)
        {
            return await DeleteByIdsAsync(ids.Select(x => (dynamic)x).ToArray());
        }
        /// <summary>
        /// 异步按条件删除
        /// </summary>
        /// <param name="whereSql">条件语句 如："Age > @Age"</param>
        /// <param name="parameters">条件参数及值 如：new { Age = 30 }</param>
        /// <returns></returns>
        public virtual async Task<bool> DeleteByWhereAsync(string whereSql = "", object? parameters = null)
        {
            if (!string.IsNullOrEmpty(whereSql) && parameters != null)
            {
                try
                {
                    return await Db.Deleteable<T>().Where(whereSql, parameters).ExecuteCommandAsync() > 0;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "条件语句：{0}；参数：{1}", whereSql, parameters);
                }
            }
            return false;
        }
        #endregion 异步删除

        #region 事务
        /// <summary>
        /// 异步多表多数据操作批量插入、更新、删除--事务
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="commandTimeout">超时</param>
        /// <returns></returns>
        public async Task<Tuple<bool, string>> ExecuteTransactionAsync(List<Tuple<string, object?>> trans, int? commandTimeout = null)
        {
            if (trans.Count == 0) return new Tuple<bool, string>(false, "执行事务SQL语句不能为空！");
            unitOfWork.BeginTran();
            try
            {
                foreach (var tran in trans)
                {
                    await Db.Ado.ExecuteCommandAsync(tran.Item1, tran.Item2);
                }
                //提交事务
                unitOfWork.CommitTran();
                return new Tuple<bool, string>(true, string.Empty);
            }
            catch (Exception ex)
            {
                //回滚事务
                logger.LogError(ex.ToString());
                unitOfWork.RollbackTran();
                return new Tuple<bool, string>(false, ex.ToString());
            }
        }
        /// <summary>
        /// 异步使用事务
        /// </summary>
        /// <param name="action">事务执行的方法</param>
        /// <returns></returns>
        public async Task<DbResult<bool>> UseTranAsync(Func<Task> action)
        {
            return await Db.Ado.UseTranAsync(() => action());
        }
        #endregion 事务
        #endregion 异步方法

        #endregion  SqlSugar 操作

        #region 辅助类方法

        /// <summary>
        /// 验证是否存在注入代码(条件语句）
        /// </summary>
        /// <param name="inputData"></param>
        public virtual bool HasInjectionData(string inputData)
        {
            if (string.IsNullOrEmpty(inputData))
                return false;

            //里面定义恶意字符集合
            //验证inputData是否包含恶意集合
            if (Regex.IsMatch(inputData.ToLower(), GetRegexString()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取正则表达式
        /// </summary>
        /// <returns></returns>
        private static string GetRegexString()
        {
            //构造SQL的注入关键字符
            string[] strBadChar =
            {
                "select\\s",
                "from\\s",
                "insert\\s",
                "delete\\s",
                "update\\s",
                "drop\\s",
                "truncate\\s",
                "exec\\s",
                "count\\(",
                "declare\\s",
                "asc\\(",
                "mid\\(",
                //"char\\(",
                "net user",
                "xp_cmdshell",
                "/add\\s",
                "exec master.dbo.xp_cmdshell",
                "net localgroup administrators"
            };

            //构造正则表达式
            string str_Regex = ".*(";
            for (int i = 0; i < strBadChar.Length - 1; i++)
            {
                str_Regex += strBadChar[i] + "|";
            }
            str_Regex += strBadChar[^1] + ").*";

            return str_Regex;
        }


        #region IDisposable Support
        private bool disposedValue = false; // 要检测冗余调用
        /// <summary>
        /// 释放托管状态
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
            Dispose(true);
            // TODO: 如果在以上内容中替代了终结器，则取消注释以下行。
            // GC.SuppressFinalize(this);
        }

        #endregion
        #endregion
    }
}
